package com.yc.cloud.admin.service.impl;

import com.yc.cloud.entity.UmsResource;
import com.yc.cloud.mapper.UmsResourceMapper;
import com.yc.cloud.mapper.UmsRoleResourceRelationMapper;
import com.yc.cloud.admin.service.UmsResourceService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yc.cloud.basic.dto.BaseQueryParam;
import lombok.val;
import cn.hutool.core.util.StrUtil;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

import java.util.List;

/**
 * <p>
 * 后台资源表 服务实现类
 * </p>
 *
 * @author JackGu
 * @since 2022-09-11
 */
@Service
public class UmsResourceServiceImpl extends ServiceImpl<UmsResourceMapper, UmsResource> implements UmsResourceService {

    @Resource
    private UmsResourceMapper umsResourceMapper;

    @Resource
    private UmsRoleResourceRelationMapper roleResourceRelationMapper;


    @Override
    public IPage<UmsResource> list(BaseQueryParam queryParam, Integer categoryId) {
        val query = new QueryWrapper<UmsResource>();
        IPage<UmsResource> page;
        //排序
        if (StrUtil.isNotEmpty(queryParam.getSortBy())) {
            if (BaseQueryParam.ORDER_DESC.equals(queryParam.getOrder())) {
                query.orderByDesc(UmsResource.ID);
            } else if (BaseQueryParam.ORDER_ASC.equals(queryParam.getOrder())) {
                query.orderByAsc(UmsResource.ID);
            }
        }

        if (categoryId != null) {
            query.eq(UmsResource.CATEGORY_ID, categoryId);
        }
        //模糊查询
        val keyword = queryParam.getKeyword();
        if (StrUtil.isNotEmpty(keyword)) {
            query.and(queryWrapper -> {
                queryWrapper.like(UmsResource.NAME, keyword).or().like(UmsResource.DESCRIPTION, keyword).or().like(UmsResource.URL, keyword);
            });
        }
        //分页
        if (queryParam.getPage()) {
            page = new Page<>(queryParam.getPageNum(), queryParam.getPageSize(), true);
        } else {
            page = new Page<>(queryParam.getPageNum(), umsResourceMapper.selectCount(query), true);
        }
        return umsResourceMapper.selectPage(page, query);
    }


    @Override
    public List<UmsResource> queryByRoleId(Long roleId) {
        return roleResourceRelationMapper.queryByRoleId(roleId);
    }
}
